﻿/***************************************************************************
 *
 * Copyright (c) 2022 vxrtc.com, Inc. All Rights Reserved
 * $Id$
 *
 **************************************************************************/

/**
 * @file network.cpp
 * @version $Revision$
 * @brief
 *
 **/

#include "ice/base/network.h"

#if defined(ICE_POSIX)
#include <ifaddrs.h>
#elif defined(ICE_WIN)
#include <iphlpapi.h>

#include "rtc_base/win32.h"
#endif

#include <rtc_base/logging.h>
#include <rtc_base/string_utils.h>

namespace ice
{

    NetworkManager::NetworkManager() = default;

    NetworkManager::~NetworkManager()
    {
        for (auto network : network_list_)
        {
            delete network;
        }

        network_list_.clear();
    }

    int NetworkManager::CreateNetworks(const NetworkConfig &config)
    {
        RTC_LOG(LS_INFO) << "==================CreateNetworks=================";

        struct ifaddrs *interface;
        int err = getifaddrs(&interface);
        if (err != 0)
        {
            RTC_LOG(LS_WARNING) << "getifaddrs error: " << strerror(errno)
                                << ", errno: " << errno;
            return -1;
        }

        for (auto cur = interface; cur != nullptr; cur = cur->ifa_next)
        {
            RTC_LOG(LS_INFO) << "interface name : " << cur->ifa_name;
            if (cur->ifa_addr->sa_family != AF_INET)
            {
                continue;
            }

            struct sockaddr_in *addr = (struct sockaddr_in *)(cur->ifa_addr);
            rtc::IPAddress ip_address(addr->sin_addr);
#if 0
        if (rtc::IPIsPrivateNetwork(ip_address) || rtc::IPIsLoopback(ip_address)) {
            continue;
        }
#else
            RTC_LOG(LS_INFO) << "config=> disable_private_ip:  " << config.disable_private_ip;

            if (rtc::IPIsLoopback(ip_address))
            {
                continue;
            }
#endif

            Network *network = new Network(cur->ifa_name, ip_address);

            RTC_LOG(LS_INFO) << "=====gathered network interface: " << network->ToString();

            network_list_.push_back(network);
        }

        freeifaddrs(interface);

        return 0;
    }



} // namespace ice
